package com.dmgis.hndz.service.impl;

import com.dmgis.entity.*;
import com.dmgis.hndz.sddz.service.Zdda01aService;
import com.dmgis.hndz.service.CommonService;
import com.dmgis.hndz.pojo.Location;
import com.dmgis.hndz.pojo.YjqDto;
import com.dmgis.hndz.pojo.YjqQueryCountryDto;
import com.dmgis.hndz.pojoVo.CountryVO;
import com.dmgis.service.DmServiceConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class CommonServiceImpl implements CommonService {
    @Value("${dmgis.ip}")
    private String dmgisIp;
    @Value("${dmgis.port}")
    private String dmgisPort;
    @Value("${dmgis.serveName}")
    private String serveName;
    //注入zdda01a的service
    @Autowired
    private Zdda01aService zdda01aService;

    @Override
    public List<CountryVO> getCountry(YjqQueryCountryDto yjqQueryCountryDto) throws IOException {
        Map<String, String> map = new HashMap<>();
        List<CountryVO> layerCountry = new ArrayList<>();
        List<YjqDto> yjqDtoList = yjqQueryCountryDto.getYjqDtoList();
        Map<String, List<YjqDto>> typeAndYjqMap = new HashMap<>();
        for (YjqDto yjqDto : yjqDtoList) {
            List<YjqDto> yjqDtoList1 = new ArrayList<>();
            if (typeAndYjqMap.containsKey(yjqDto.getLevel())) {
                yjqDtoList1 = typeAndYjqMap.get(yjqDto.getLevel());
            }
            yjqDtoList1.add(yjqDto);
            typeAndYjqMap.put(yjqDto.getLevel(), yjqDtoList1);
        }
        for (Map.Entry<String, List<YjqDto>> entry : typeAndYjqMap.entrySet()) {
            List<String[]> posList = new ArrayList<>();
            String type = entry.getKey();
            List<YjqDto> yjqDtoList1 = entry.getValue();
            for (YjqDto yjqDto : yjqDtoList1) {
                posList.add(yjqDto.getPos());
            }
            //在这个地方进行判断省市县三级
//            if (yjqQueryCountryDto.getAreaCode().equals("370100")) {
//                layerCountry.addAll(getLayerCountry1(posList, type));
//            } else if (yjqQueryCountryDto.getAreaCode().equals("370112")) {
//                layerCountry.addAll(getLayerCountry2(posList, type));
//            } else {
//                layerCountry.addAll(getLayerCountry(posList, type));
//            }

            if (yjqQueryCountryDto.getAreaCode().endsWith("0000")) {
                layerCountry.addAll(getLayerCountry(posList, type));
            } else if (yjqQueryCountryDto.getAreaCode().endsWith("00")) {
                layerCountry.addAll(getLayerCountry1(posList, type));
            } else {
                layerCountry.addAll(getLayerCountry2(posList, type));
            }

//            Set<Map.Entry<String, String>> entries = layerCountry.entrySet();
//            for (Map.Entry<String, String> stringStringEntry : entries) {
//                if (!map.containsKey(stringStringEntry.getKey())) {
//                    map.put(stringStringEntry.getKey(), stringStringEntry.getValue());
//                } else {
//                    String oldType = map.get(stringStringEntry.getKey());
//                    int oldTypeNumber = Integer.parseInt(oldType);
//                    int newTypeNumber = Integer.parseInt(stringStringEntry.getValue());
//                    if (newTypeNumber > oldTypeNumber) {
//                        map.put(stringStringEntry.getKey(), stringStringEntry.getValue());
//                    }
//                }
//            }
        }
        Set<Map.Entry<String, String>> entries = map.entrySet();
        String type = yjqQueryCountryDto.getType();
        if (type != null) {
            if (type.equals("城市内涝")) {
                for (CountryVO entry : layerCountry) {
                    String value = "";
                    switch (entry.getType()) {
                        case "0":
                            value = "风险较小";
                            break;
                        case "1":
                            value = "风险较大";
                            break;
                        case "2":
                            value = "风险大";
                            break;
                        case "3":
                            value = "风险大";
                            break;
                        case "4":
                            value = "风险极大";
                            break;
                    }
                    entry.setType(value);
                }
            } else {
                for (CountryVO entry : layerCountry) {
                    String value = "";
                    switch (entry.getType()) {
                        case "0":
                            value = "风险较大";
                            break;
                        case "1":
                            value = "风险大";
                            break;
                        case "2":
                            value = "风险极大";
                            break;
                    }
                    entry.setType(value);
                }
            }
        }
        // 部分数据返回为null异常
//        if (layerCountry.size() > 0) {
//            layerCountry.forEach(l -> {
//                if (StringUtil.IsNullOrEmpty(l.getCounty())) {
//                    l.setCounty("暂无");
//                }
//            });
//        }
        return layerCountry;
    }

    /**
     * 多边形查询乡镇点
     *
     * @param posList 点集
     * @param type
     * @return
     * @throws UnsupportedEncodingException
     */
    private List<CountryVO> getLayerCountry(List<String[]> posList, String type) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (String[] pos : posList) {
            for (String po : pos) {
                String[] posStr = po.split(" ");
                DmMapPoint dmMapPoint = new DmMapPoint();
                dmMapPoint.setX(Double.parseDouble(posStr[0]));
                dmMapPoint.setY(Double.parseDouble(posStr[1]));
                sb.append(dmMapPoint.getX()).append(" ").append(dmMapPoint.getY()).append(";");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("*");
        }
        sb.deleteCharAt(sb.length() - 1);
        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
        String xml = "";
        //属性服务
        DmFeatureMapService dmFeatureMapService = new DmFeatureMapService();
        dmFeatureMapService.setStrLayerName("县界面");
        DmFeatureParam dmFeatureParam = new DmFeatureParam();
        dmFeatureParam.setAttribute(1);
        dmFeatureParam.setFeatureLimit(0);
        dmFeatureMapService.setParam(dmFeatureParam);
        dmFeatureMapService.setType("0");
        DmSql dmSql = new DmSql();
        dmSql.setStrPos(sb.toString());
        dmFeatureMapService.setM_sql(dmSql);
        xml = dmFeatureMapService.getXmlString();
        String res = conn.getServiceXml(serveName, 2, xml);
        ArrayList<CountryVO> countryVOS = new ArrayList<>();
        //String  res = "http://localhost:8097/dms/GetFeature/hndl?param="+xml;
        //  DmGetFeature feature = mapXML.dmGetFeatureInfo(res);
        List<Location> locations = parseXML(res);
        for (Location location : locations) {
            CountryVO countryVO = new CountryVO();
            //根据查询出来的code截取前四位来查询数据库找到对应的市级
            String code = location.getCode();
            String cityCode = code.substring(0, 4) + "00";
            //根据市级code查询市级名称
            String cityName = zdda01aService.queryCityName(cityCode);
            countryVO.setCounty(cityName);
            countryVO.setTown(location.getName());
            countryVO.setType(type);
            countryVOS.add(countryVO);
        }
        return countryVOS;
    }

    public static List<Location> parseXML(String xmlData) {
        List<Location> locations = new ArrayList<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlData)));
            NodeList featureList = document.getElementsByTagName("FEATURE");
            for (int i = 0; i < featureList.getLength(); i++) {
                Element feature = (Element) featureList.item(i);
                Element fields = (Element) feature.getElementsByTagName("FIELDS").item(0);
                Location location = new Location();
                location.setDmgisId(fields.getAttribute("dmgis_id"));
                location.setObjectId(fields.getAttribute("OBJECTID"));
                location.setElemId(fields.getAttribute("ELEMID"));
                location.setName(fields.getAttribute("NAME"));
                location.setPac(fields.getAttribute("PAC"));
                location.setProDate(fields.getAttribute("PRODATE"));
                location.setSource(fields.getAttribute("SOURCE"));
                location.setPrctag(fields.getAttribute("PRCTAG"));
                location.setCc(fields.getAttribute("CC"));
                location.setAscription(fields.getAttribute("ASCRIPTION"));
                location.setEname(fields.getAttribute("ENAME"));
                location.setChangeAtt(fields.getAttribute("CHANGEATT"));
                location.setShapeLeng(fields.getAttribute("Shape_Leng"));
                location.setShapeArea(fields.getAttribute("Shape_Area"));
                location.setCounty(fields.getAttribute("ENAME"));
                location.setCode(fields.getAttribute("CODE"));
                location.setProvince(fields.getAttribute("PROVINCE"));
                location.setCity(fields.getAttribute("CITY"));
                location.setCountry(fields.getAttribute("COUNTY"));
                location.setTown(fields.getAttribute("TOWN"));
                locations.add(location);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locations;
    }

    //市级传入乡界面
    private List<CountryVO> getLayerCountry1(List<String[]> posList, String type) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (String[] pos : posList) {
            for (String po : pos) {
                String[] posStr = po.split(" ");
                DmMapPoint dmMapPoint = new DmMapPoint();
                dmMapPoint.setX(Double.parseDouble(posStr[0]));
                dmMapPoint.setY(Double.parseDouble(posStr[1]));
                sb.append(dmMapPoint.getX()).append(" ").append(dmMapPoint.getY()).append(";");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("*");
        }
        sb.deleteCharAt(sb.length() - 1);
        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
        String xml = "";
        //属性服务
        DmFeatureMapService dmFeatureMapService = new DmFeatureMapService();
        dmFeatureMapService.setStrLayerName("乡界面");
        DmFeatureParam dmFeatureParam = new DmFeatureParam();
        dmFeatureParam.setAttribute(1);
        dmFeatureParam.setFeatureLimit(0);
        dmFeatureMapService.setParam(dmFeatureParam);
        dmFeatureMapService.setType("0");
        DmSql dmSql = new DmSql();
        dmSql.setStrPos(sb.toString());
        dmFeatureMapService.setM_sql(dmSql);
        xml = dmFeatureMapService.getXmlString();
        String res = conn.getServiceXml(serveName, 2, xml);
        ArrayList<CountryVO> countryVOS = new ArrayList<>();
        //String  res = "http://localhost:8097/dms/GetFeature/hndl?param="+xml;
        //  DmGetFeature feature = mapXML.dmGetFeatureInfo(res);
        List<Location> locations = parseXML(res);
        for (Location location : locations) {
            CountryVO countryVO = new CountryVO();
//            //根据查询出来的code截取前四位来查询数据库找到对应的市级
//            String code = location.getCode();
//            String cityCode = code.substring(0, 6);
//            //根据县级code查询市级名称
//            String cityName = zdda01aService.queryCityName(cityCode);
            countryVO.setCounty(location.getCountry());
            countryVO.setTown(location.getTown());
            countryVO.setType(type);
            countryVOS.add(countryVO);
        }
        return countryVOS;
    }

    //县级传入村庄界面
    private List<CountryVO> getLayerCountry2(List<String[]> posList, String type) throws IOException {
        StringBuilder sb = new StringBuilder();
        for (String[] pos : posList) {
            for (String po : pos) {
                String[] posStr = po.split(" ");
                DmMapPoint dmMapPoint = new DmMapPoint();
                dmMapPoint.setX(Double.parseDouble(posStr[0]));
                dmMapPoint.setY(Double.parseDouble(posStr[1]));
                sb.append(dmMapPoint.getX()).append(" ").append(dmMapPoint.getY()).append(";");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("*");
        }
        sb.deleteCharAt(sb.length() - 1);
        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
        String xml = "";
        //属性服务
        DmFeatureMapService dmFeatureMapService = new DmFeatureMapService();
        dmFeatureMapService.setStrLayerName("村庄");
        DmFeatureParam dmFeatureParam = new DmFeatureParam();
        dmFeatureParam.setAttribute(1);
        dmFeatureParam.setFeatureLimit(0);
        dmFeatureMapService.setParam(dmFeatureParam);
        dmFeatureMapService.setType("0");
        DmSql dmSql = new DmSql();
        dmSql.setStrPos(sb.toString());
        dmFeatureMapService.setM_sql(dmSql);
        xml = dmFeatureMapService.getXmlString();
        String res = conn.getServiceXml(serveName, 2, xml);
        ArrayList<CountryVO> countryVOS = new ArrayList<>();
        //String  res = "http://localhost:8097/dms/GetFeature/hndl?param="+xml;
        //  DmGetFeature feature = mapXML.dmGetFeatureInfo(res);
        List<Location> locations = parseXML(res);
        for (Location location : locations) {
            CountryVO countryVO = new CountryVO();
//            //根据查询出来的code截取前四位来查询数据库找到对应的市级
//            String code = location.getCode();
//            String cityCode = code.substring(0, 9);
//            //根据市级code查询市级名称
//            String cityName = zdda01aService.queryCityName(cityCode);
            countryVO.setCounty(location.getName());
            countryVO.setTown(location.getTown());
            countryVO.setType(type);
            countryVOS.add(countryVO);
        }
        return countryVOS;
    }
}
